using System.Collections.Generic;

namespace dbm2.Model
{
    public class Table
    {
        private List<Field> fields;
        private List<Index> indexes;

        public string Name { get; private set; }
        public string Schema { get; private set; }

        public Table(string name, string schemaName = null)
        {
            Name = name;
            Schema = schemaName;
            fields = new List<Field>();
            indexes = new List<Index>();
        }

        public void AddField(Field field)
        {
            if(!IsContainsFieldWithName(field.Name) && field.GetParentTable() == null)
            {
                fields.Add(field);
                field.SetTable(this);
            }
        }

        private bool IsContainsFieldWithName(string fieldName)
        {
            foreach (var field in fields)
                if (field.Name.Equals(fieldName))
                    return true;
            return false;
        }

        public int CountFields()
        {
            return fields.Count;
        }

        public bool IsContainsField(Field field)
        {
            if (fields.Contains(field))
                return true;
            return false;
        }

        public Field GetField(string name)
        {
            foreach (var field in fields)
            {
                if (field.Name == name)
                    return field;
            }
            return null;
        }

        public Index[] GetIndexes()
        {
            return indexes.ToArray();
        }

        public void AddIndex(Index index)
        {
            indexes.Add(index);
            index.ParentTable = this;
        }

        public Field[]  GetFields()
        {
            return fields.ToArray();
        }

        public Index GetIndex(string indexName)
        {
            foreach (var index in indexes)
            {
                if (index.Name == indexName)
                    return index;
            }
            return null;
        }
    }
}